package party.lovey.remote.amq;

/**
 * Created by huhaichao on 2017/3/18.
 */


import org.apache.commons.lang3.StringUtils;
import party.lovey.remote.utils.Consts;
import party.lovey.remote.utils.SerializeUtil;

import javax.jms.*;

/**
 * activemq message receiver
 */
public class Receiver {


    // Session： 一个发送或接收消息的线程
    private static Session session;


    /**
     * 接收消息
     * @param queueName
     * @return
     */
    public static synchronized Message receiveMessage(String queueName) {
        session = SessionFactory.getReceiverSession();
        MessageConsumer consumer = getMessageConsumer(queueName);

        Message message = null;
        try {
            message = consumer.receive();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return message;
    }

    private static MessageConsumer consumer = null;
    private static MessageConsumer getMessageConsumer(String queueName) {
        if(consumer!=null){
            return consumer;
        }
        // Destination ：消息的目的地;消息发送给谁.
        Destination destination;
        // 消费者，消息接收者

        try {
            // 获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置
            destination = session.createQueue(queueName);
            consumer = session.createConsumer(destination);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return consumer;
    }

    /**
     * 接受二进制消息
     * @param queueName
     * @return
     */
    public static byte[]  receiveBinaryMessage(String queueName){
        Message message = receiveMessage(queueName);
        BytesMessage bytesMessage = (BytesMessage) message;
        try {
            long len = bytesMessage.getLongProperty(Consts.LENGTH);
            byte[] bytes=new byte[(int) len];
            bytesMessage.readBytes(bytes);
            return bytes;
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    /**
     * 接受object消息
     * @param queueName
     * @return
     */
    public static Object receiveObjectMessage(String queueName) {
        Message message = receiveMessage(queueName);
        TextMessage textMessage = (TextMessage) message;
        try {
            String text = textMessage.getText();
            if(StringUtils.isNotBlank(text)){
                return SerializeUtil.fromXML(text);
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return null;
    }


}